#include "dcsfileoperator.h"

#include <QFile>
#include <QDebug>

DCSFileOperator::DCSFileOperator(const QString &fileName)
{
    mFileOp = new QFile(fileName);
    mMeta = new struct meta_sector();
}

DCSFileOperator::~DCSFileOperator()
{
    delete mFileOp;
    delete mMeta;
}

bool DCSFileOperator::fileOpen()
{
    if (!mFileOp->open(QIODevice::ReadOnly))
    {
        qDebug() << "file open error";
        return false;
    }

    return true;
}

void DCSFileOperator::fileClose()
{
    mFileOp->close();
}

/**
 * @brief DCSFileOperator::readMetaData
 *          读取脱机文件的元数据
 * @return
 */
bool DCSFileOperator::readMetaData()
{
    qint64 rdsize;

    if (!mFileOp->seek(0))
    {
        qDebug() << "file seek error";
        return false;
    }

    rdsize = mFileOp->read((char *) mMeta, SECTOR_SIZE);

    qDebug() << "read size:" << rdsize;

    return true;
}

struct meta_sector *DCSFileOperator::meta() const
{
    return mMeta;
}

/**
 * @brief DCSFileOperator::readOneFrameByNum
 *          读取脱机文件视频数据的第 frameNum 个帧到data里面
 * @param data
 * @param sectorNum
 * @return
 */
qint64 DCSFileOperator::readOneFrameByNum(QByteArray &data, unsigned int frameNum)
{
    qint64 rdSize;
    qint64 seekPos;
    int frameSize;

    seekPos = (mMeta->stream_start_sector_num + frameNum * mMeta->sector_per_frame) * SECTOR_SIZE;
    frameSize = mMeta->sector_per_frame * SECTOR_SIZE;

    if (!mFileOp->seek(seekPos))
    {
        qDebug() << "file seek error";
        return -1;
    }

    data.resize(frameSize);

    rdSize = mFileOp->read(data.data(), frameSize);

//    qDebug() << "read size:" << rdSize;

    return rdSize;
}
